package com.lanyan.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.core.domain.BaseEntity;
import com.lanyan.common.core.domain.PageR;
import com.lanyan.common.core.domain.R;
import com.lanyan.common.core.page.TableDataInfo;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.framework.web.service.SysLoginService;
import com.lanyan.system.domain.*;
import com.lanyan.system.domain.vo.*;
import com.lanyan.system.mapper.ClassifyMapper;
import com.lanyan.system.service.*;
import com.lanyan.web.core.config.WxConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@Api(tags = {"公共"})
@RequestMapping("public")
public class PublicController extends BaseController {
    @Autowired
    private IClassifyService classifyService;
    @Autowired
    private IIndexImgService indexImgService;
    @Autowired
    private ISettingService settingService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IProductService productService;
    @Autowired
    private ISkuNameService skuNameService;
    @Autowired
    private ISkuValueService skuValueService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private IVipSettingService vipSettingService;
    @Autowired
    private IEvaluateService evaluateService;
    @Autowired
    private IHotSearchService hotSearchService;
    @Autowired
    private ICourierService courierService;
    @Autowired
    private ITypeService typeService;
    @Autowired
    private IPaySettingService paySettingService;
    @Autowired
    private ITimeSettingService timeSettingService;
    @Autowired
    private ClassifyMapper classifyMapper;

    /**
     * 查询时间设置列表
     */
    @GetMapping("/listTimeSetting")
    @ApiOperation("查询时间设置列表")
    public R<List<TimeSetting>> listTimeSetting() {
        List<TimeSetting> list = timeSettingService.selectTimeSettingList(new TimeSetting());
        return R.ok(list);
    }


    /**
     * 查询充值设置列表
     */
    @GetMapping("/paySetting")
    @ApiOperation("查询充值设置列表")
    public R<List<PaySetting>> paySetting() {
        List<PaySetting> list = paySettingService.lambdaQuery()
                .eq(PaySettingVo::getDelFlag, "0")
                .orderByAsc(PaySettingVo::getPrice)
                .list();
        return R.ok(list);
    }

    /**
     * 获取物品类型
     */
    @GetMapping("/listType")
    @ApiOperation("获取物品类型")
    public R<List<Type>> listType() {
        List<Type> list = typeService.lambdaQuery()
                .eq(TypeVo::getDelFlag,"0")
                .orderByAsc(TypeVo::getName)
                .list();
        return R.ok(list);
    }

    /**
     * 获取会员支付设置
     */
    @GetMapping("/listVipSetting")
    @ApiOperation("获取会员支付设置")
    public R<List<VipSetting>> listVipSetting() {
        List<VipSetting> list = vipSettingService.lambdaQuery()
                .eq(VipSetting::getDelFlag, "0")
                .orderByAsc(VipSetting::getTimer)
                .list();
        return R.ok(list);
    }

    /**
     * 首页轮播
     */
    @GetMapping("/listIndexImg")
    @ApiOperation("首页轮播")
    public R<List<String>> listIndexImg() {
        List<IndexImg> list = indexImgService.lambdaQuery()
                .eq(IndexImg::getDelFlag, "0")
                .orderByAsc(IndexImgVo::getSort)
                .list();
        List<String> collect = list.stream().map(IndexImgVo::getImgUrl).collect(Collectors.toList());
        return R.ok(collect);
    }

    /**
     * 获取小区
     */
    @GetMapping("/listEstate")
    @ApiOperation("获取小区")
    public R<List<Estate>> listEstate(String name,String latitude, String longitude) {
        List<Estate> list = estateService.getSort(name,latitude, longitude);
        return R.ok(list);
    }

    /**
     * 获取楼栋
     */
    @GetMapping("/listBuilding")
    @ApiOperation("获取楼栋")
    public R<List<Building>> listBuilding(long estateId) {
        List<Building> list = buildingService.lambdaQuery()
                .eq(BuildingVo::getDelFlag, "0")
                .eq(BuildingVo::getEstateId, estateId)
                .orderByAsc(BuildingVo::getName)
                .list();
        return R.ok(list);
    }

    /**
     * 查询分类列表
     */
    @GetMapping("/listClassify")
    @ApiOperation("查询分类")
    public AjaxResult listClassify() {
        List<Classify> list = classifyService.lambdaQuery()
                .eq(ClassifyVo::getDelFlag, "0")
                .isNull(ClassifyVo::getSuperior)
                .orderByAsc(ClassifyVo::getSort)
                .list();
        for (Classify item : list) {
            item.setChildren(classifyService.lambdaQuery()
                    .eq(ClassifyVo::getDelFlag, "0")
                    .eq(ClassifyVo::getSuperior, item.getClassifyId())
                    .orderByAsc(ClassifyVo::getSort)
                    .list());
        }
        return success(list);
    }

    /**
     * 获取设置详细信息
     */
    @GetMapping("/getSetting")
    @ApiOperation("获取设置详细信息")
    public AjaxResult getSetting(String groupKey,String valueKey) {
        if (StringUtils.isEmpty(groupKey)){
            return AjaxResult.success(settingService.lambdaQuery().eq(SettingVo::getDelFlag,"0").list());
        }else if (StringUtils.isEmpty(valueKey)){
            List<Setting> list = settingService.lambdaQuery()
                    .eq(SettingVo::getDelFlag, "0")
                    .eq(SettingVo::getGroupKey, groupKey)
                    .orderByAsc(SettingVo::getValueSort)
                    .list();
            Map res = new HashMap();
            for (Setting setting : list) {
                res.put(setting.getValueKey(),setting.getValue());
            }
            return AjaxResult.success(res);
        }else {
            Setting setting = settingService.lambdaQuery()
                    .eq(SettingVo::getDelFlag, "0")
                    .eq(SettingVo::getGroupKey, groupKey)
                    .eq(SettingVo::getValueKey, valueKey)
                    .one();
            return AjaxResult.success("获取成功",setting.getValue());
        }
    }

    /**
     * 查询商品列表
     */
    @GetMapping("/pageProduct")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "topClassifyId", value = "一级分类id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "classifyId", value = "所属分类", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "isCommend", value = "是否推荐(0不推荐 1推荐)", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "pageNum", value = "第几页", dataType = "int", dataTypeClass = int.class),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", dataTypeClass = int.class),
    })
    @ApiOperation("查询商品列表")
    public PageR<Product> pageProduct(@ApiIgnore Product product) {
        if (StringUtils.isNotEmpty(product.getName())){
            HotSearch old = hotSearchService.lambdaQuery()
                    .eq(HotSearchVo::getDelFlag, "0")
                    .eq(HotSearchVo::getName, product.getName())
                    .one();
            if (old != null){
                old.setNum(old.getNum() + 1 );
            }else {
                old = new HotSearch();
                old.setName(product.getName());
                old.setNum(1L);
            }
            hotSearchService.saveOrUpdate(old);
        }
        startPage();
        product.setIsSale("1");
        product.setDelFlag("0");
        List<Product> list = new ArrayList<>();
        //一级分类不为空、二级分类为空
        if (product.getTopClassifyId() != null && product.getClassifyId() == null){
            LambdaQueryWrapper<Classify> classifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
            classifyLambdaQueryWrapper
                    .eq(Classify::getSuperior, product.getTopClassifyId());
            List<Classify> classifies = classifyMapper.selectList(classifyLambdaQueryWrapper);
            Set<Long> collect = classifies.stream().map(Classify::getClassifyId).collect(Collectors.toSet());
            product.setClassIdList(collect);
            list = productService.selectProductListClass(product);
        }else {
            list = productService.selectProductList(product);
        }
        return PageR.page(list);
    }

    /**
     * 查询商品详情
     */
    @GetMapping("/productDetails")
    @ApiOperation("查询商品详情")
    public R<Product> productDetails(Long productId) {
        Product product = productService.getById(productId);
        List<SkuName> sns = skuNameService.lambdaQuery()
                .eq(SkuName::getDelFlag, "0")
                .eq(SkuName::getProductId, productId)
                .list();
        for (SkuName sn : sns) {
            List<SkuValue> svs = skuValueService.lambdaQuery()
                    .eq(SkuValue::getDelFlag, "0")
                    .eq(SkuValue::getSkuNameId, sn.getSkuNameId())
                    .list();
            sn.setSvs(svs);
        }
        product.setSns(sns);
        List<Sku> skus = skuService.lambdaQuery()
                .eq(Sku::getDelFlag, "0")
                .eq(Sku::getProductId, productId)
                .list();
        for (Sku sku : skus) {
            if (StringUtils.isEmpty(sku.getImage())) {
                sku.setImage(product.getMainImg());
            }
        }
        product.setSkus(skus);
        product.setIsTimely(Optional.ofNullable(classifyService.getById(product.getTopClassifyId())).map(ClassifyVo::getIsTimely).orElse("0"));
        return R.ok(product);
    }

    /**
     * 查询商品评价
     */
    @GetMapping("/pageComment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "t", value = "0-好评 1-中评 2-差评 3-有图", dataType = "int", dataTypeClass = int.class),
            @ApiImplicitParam(name = "productId", value = "所属商品", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "pageNum", value = "第几页", dataType = "int", dataTypeClass = int.class),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", dataTypeClass = int.class),
    })
    @ApiOperation("查询商品评价")
    public R<Map> pageComment(@ApiIgnore Evaluate evaluate) {
        startPage();
        List<Evaluate> list = evaluateService.lambdaQuery()
                .eq(EvaluateVo::getDelFlag, "0")
                .eq(EvaluateVo::getProductId, evaluate.getProductId())
                .orderByDesc(BaseEntity::getCreateTime)
                .list();
        for (Evaluate item : list) {
            item.setAccount(accountService.getById(item.getAccountId()));
        }
        Map<String, Object> res = new HashMap<>();
        PageR<Evaluate> pageR = PageR.page(list);
        res.put("data", pageR);
        res.put("all",pageR.getTotal());
        res.put("good",evaluateService.lambdaQuery()
                .eq(EvaluateVo::getDelFlag,"0")
                .eq(EvaluateVo::getProductId,evaluate.getProductId())
                .gt(EvaluateVo::getManner,"4")
                .count());
        res.put("have",evaluateService.lambdaQuery()
                .eq(EvaluateVo::getDelFlag,"0")
                .eq(EvaluateVo::getProductId,evaluate.getProductId())
                .isNotNull(EvaluateVo::getImage)
                .count());
        return R.ok(res);
    }

    /**
     * 获取热搜
     */
    @GetMapping("/getHotSearch")
    @ApiOperation("获取热搜")
    public R<List<String>> getHotSearch() {
        Page<HotSearch> page = new Page();
        page.setCurrent(1);
        page.setSize(10);
        page = hotSearchService.lambdaQuery()
                .eq(HotSearchVo::getDelFlag,"0")
                .orderByDesc(HotSearchVo::getNum)
                .page(page);
        List<HotSearch> records = page.getRecords();
        List<String> collect = records.stream().map(HotSearchVo::getName).collect(Collectors.toList());
        return R.ok(collect);
    }

    /**
     * 获取某个配送员
     */
    @GetMapping("/getCourier")
    @ApiOperation("获取某个配送员")
    public R<Courier> getCourier(Long courierId) {
        return R.ok(courierService.getById(courierId));
    }

    @Autowired
    private SysLoginService loginService;

    /**
     * test
     */
    @GetMapping("/test")
    @ApiOperation("test")
    public AjaxResult test(String openId) {
        // 获取当前日期
        String token = loginService.weChatLogin(openId);
        return success(token);
    }
}
